package top.infopub.mgr.sys.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.hr.dao.StaffInfoDao;
import top.infopub.mgr.mkt.domain.CollectDomain;
import top.infopub.mgr.sys.dao.OperatorDao;
import top.infopub.mgr.sys.dao.OperatorroleDao;
import top.infopub.mgr.sys.domain.OperatorDomain;
import top.infopub.mgr.sys.service.OperatorService;
import top.infopub.mgr.sys.vo.OperatorVo;
import top.infopub.mgr.util.EnumDefinition;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.sys.Operator;
import top.infopub.model.sys.Operatorrole;
import top.infopub.security.core.CaptchaUsernamePasswordToken;
import top.infopub.security.service.SysUserService;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.DateUtil;
import top.infopub.util.MD5;

import java.util.List;


@Service
public class OperatorServiceImpl extends GenericServiceImpl<Operator, String> implements OperatorService, SysUserService {

    @Autowired
    private OperatorDao operatorDao;

    @Autowired
    private OperatorroleDao operatorroleDao;

    @Autowired
    private StaffInfoDao staffInfoDao;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Override
    public GenericDao<Operator, String> getDao() {
        return operatorDao;
    }

    @Override
    public AuthorizationVO getUserByUserName(CaptchaUsernamePasswordToken loginObj) {
        Operator po = this.operatorDao.selectByUserName(loginObj.getUsername());
        if (po == null) {
            return null;
        }
        AuthorizationVO vo = new AuthorizationVO();
        if (po.getBisFreeze().equals(EnumDefinition.SysUserStatus.FREEZE.getCode())) {
            vo.setFreeze(true);
        }
        vo.setId(po.getId());
        vo.setUserName(po.getSuserName());
        vo.setPassword(po.getSpassword());
        if (po.getDlastLoginTime() != null) {
            vo.setLastLoginTime(DateFormatUtils.format(po.getDlastLoginTime(),
                DateUtil.DATE_STYLE_SIMPLE));
        }
        else {
            vo.setLastLoginTime(DateUtil.currentDate(DateUtil.DATE_STYLE_BASIC));
        }
        return vo;
    }

    @Override
    public AuthorizationVO getUserByCode(String code) {
        StaffInfo staffInfo=new StaffInfo();
        staffInfo.setCode(code);
        List<StaffInfo> staffInfos = staffInfoDao.selectByEntityWhere(staffInfo);
        if (staffInfos==null||staffInfos.size()==0){
            return null;
        }
        staffInfo=staffInfos.get(0);
        Operator po=new Operator();
        po.setHrStaffId(staffInfo.getId());
        List<Operator> operators = operatorDao.selectByEntityWhere(po);
        if (operators==null||operators.size()==0){
            return null;
        }
        po=operators.get(0);
        AuthorizationVO vo = new AuthorizationVO();
        if (po.getBisFreeze().equals(EnumDefinition.SysUserStatus.FREEZE.getCode())) {
            vo.setFreeze(true);
        }
        vo.setId(po.getId());
        vo.setUserName(po.getSuserName());
        vo.setPassword(po.getSpassword());
        vo.setRealName(po.getSrealName());
        vo.setHrStaffId(po.getHrStaffId());
        if (po.getDlastLoginTime() != null) {
            vo.setLastLoginTime(DateFormatUtils.format(po.getDlastLoginTime(),
                    DateUtil.DATE_STYLE_SIMPLE));
        }
        else {
            vo.setLastLoginTime(DateUtil.currentDate(DateUtil.DATE_STYLE_BASIC));
        }
        return vo;
    }

    @Override
    public AuthorizationVO getUserDetail(String userId) {
        AuthorizationVO dtl = new AuthorizationVO();
        Operator op = this.operatorDao.selectByPrimaryKey(userId);
        dtl.setId(op.getId());
        dtl.setCode(op.getSoperatorNo());
        dtl.setUserName(op.getSuserName());
        dtl.setRealName(op.getSrealName());
        dtl.setSex(op.getIsex());
        if (op.getDlastLoginTime() != null) {
            dtl.setLastLoginTime(DateFormatUtils.format(op.getDlastLoginTime(),
                DateUtil.DATE_STYLE_WITHOUT_SEC));
        }
        else {
            dtl.setLastLoginTime(DateUtil.currentDate(DateUtil.DATE_STYLE_WITHOUT_SEC));
        }
        dtl.setMobile(op.getSmobile());
        dtl.setEmail(op.getSmail());
        dtl.setHrStaffId(op.getHrStaffId());
        return dtl;
    }

    @Override
    public void loginSuccess(String userId, String host) {
        // 更新用户的登录时间
        this.operatorDao.updateForLoginSuccess(userId);
    }

    @Override
    public void loginError(String userId, String host) {

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOperatorRole(String checkRoleId, String operatorId) {
        // 删除已经拥有的用户
        operatorroleDao.deleteByOperatorId(operatorId);
        if (StringUtils.isNotBlank(checkRoleId)) {
            String[] roleIds = checkRoleId.split(",");
            if (roleIds != null && roleIds.length > 0) {
                for (String roleId : roleIds) {
                    Operatorrole operatorRole = new Operatorrole();
                    operatorRole.setSoperatorId(operatorId);
                    operatorRole.setSroleId(roleId);
                    operatorroleDao.insert(operatorRole);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                // 执行逻辑删除
                Operator operator = new Operator();
                operator.setBisDelete(1);
                operator.setId(id);
                operatorDao.updateByIdSelective(operator);
            }
        }
    }

    @Override
    public boolean isUsernameExist(String username) {
        return operatorDao.isUsernameExist(username) > 0;
    }

    @Override
    public void updatePassword(String userName, String password) {
        Operator operator = new Operator();
        // MD5加盐
        operator.setSpassword(MD5.salt(userName, password));
        operator.setSuserName(userName);
        operatorDao.updatePwd(operator);
    }

    @Override
    public int queryByNameAndPw(String userName, String pw) {
        Operator opt = new Operator();
        opt.setSuserName(userName);
        // MD5加盐
        opt.setSpassword(MD5.salt(userName, pw));
        return operatorDao.queryByNameAndPw(opt);
    }

    @Override
    public void logout(String arg0) {

    }

    @Override
    public Page<OperatorDomain> selectPageByDomainWhere(Page<OperatorDomain> page,
                                                        OperatorVo operatorVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<OperatorDomain>)operatorDao.selectByDomainWhere(operatorVo);
    }

    @Override
    public boolean isMobileExist(String smobile) {
        Operator operator = new Operator();
        operator.setSmobile(smobile);
        operator.setBisDelete(0);
        List<Operator> operatorList = operatorDao.selectByEntityWhere(operator);
        if (operatorList != null && operatorList.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isEmailExist(String smail) {
        Operator operator = new Operator();
        operator.setSmail(smail);
        operator.setBisDelete(0);
        List<Operator> operatorList = operatorDao.selectByEntityWhere(operator);
        if (operatorList != null && operatorList.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Operator> selectOperatorByGroupIdUser(String groupId, String roleType) {
        return operatorDao.selectOperatorByGroupIdUser(groupId,roleType);
    }

    @Override
    public List<Operator> selectOperatorByGroupIdPost(String groupId, String roleType,String orgId,String deptId) {
        return operatorDao.selectOperatorByGroupIdPost(groupId,roleType,orgId,deptId);
    }

    @Override
    public List<Operator> selectOperatorByGroupIdOrgIdsPost(String groupId, String roleType, List<String> orgIds) {
        return operatorDao.selectOperatorByGroupIdOrgIdsPost(groupId,roleType,orgIds);
    }

    public Operator selectById(String id){
        return operatorDao.selectById(id);
    }

    @Override
    public CollectDomain selectTail(String id) {
        return operatorDao.selectTail(id);
    }
}
